package com.example.weisdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.example.weisdk.entity.User;
import org.springframework.web.bind.annotation.RequestBody;


import java.util.HashMap;
import java.util.Map;

import static com.example.weisdk.utils.SignUtils.genSign;

public class Client {
    private String accessKey;
    private String secretKey;
    public Client(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }
private static final String URL="https://localhost:7530/name";
//構建一個私有方法，用於構造請求頭
    private Map<String,String>  getHashMap(String body){
        Map<String,String> hashMap=new HashMap<>();
        hashMap.put("accessKey",accessKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body",body);
        hashMap.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        hashMap.put("sign",genSign(body,secretKey));
        return hashMap;

}

    public String getNameByGet(String name){
        //可以單獨傳入http參數，這樣參數會自動做url編碼并帡接在url中
        HashMap<String,Object> paramMap=new HashMap<>();
        paramMap.put("name",name);
        //使用Http工具發起GET請求，并獲取服務器返回的結果
        String result = HttpUtil.get(URL,paramMap);

        return result;
    }
    public String getNameByPost(String name){
        HashMap<String,Object> paramMap=new HashMap<>();
        paramMap.put("name",name);
        String result = HttpUtil.post(URL,paramMap);
        return result;
    }
    public String getUserNameByPost(@RequestBody User user){
        //將user對象轉爲JSON字符串
      String json= JSONUtil.toJsonStr(user);
        HttpResponse httpResponse=HttpRequest.post("http://localhost:7536/api/name/JSON")
                .addHeaders(getHashMap(json))//添加構造的請求頭
                .body(json)//將JSON字符串設置為請求躰
                .execute();
        String result=httpResponse.body();
        return result;
    }

}
